package com.wt.demo.controller;

import com.wt.demo.pojo.ListValidate;
import com.wt.demo.pojo.ValidateEntity;
import com.wt.demo.validategroup.ValidateA;
import com.wt.demo.validategroup.ValidateB;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;

/**
 * @Description
 * @Author:wangtao
 * @Date:15:19 2017/5/27
 * @Email:tao8.wang@changhong.com
 */
@Controller
public class ValidateController {

    @RequestMapping("/test")
    @ResponseBody
    public Object test(@Validated(value = ValidateA.class) @RequestBody ValidateEntity ve, BindingResult br) {
        if (br.hasErrors()) {
            List<ObjectError> errors = br.getAllErrors();
            ObjectError error = errors.get(0);
            return "code:" + error.getCode() + " msg:" + error.getDefaultMessage() + " objectName:" + error.getObjectName() + " arguments:" + error.getArguments();
        }
        return "success";
    }

    @RequestMapping("/test2")
    @ResponseBody
    public Object test2(@Validated(value = ValidateB.class) @RequestBody ValidateEntity ve, BindingResult br) {
        if (br.hasErrors()) {
            List<ObjectError> errors = br.getAllErrors();
            ObjectError error = errors.get(0);
            return "code:" + error.getCode() + " msg:" + error.getDefaultMessage() + " objectName:" + error.getObjectName() + " arguments:" + error.getArguments();
        }
        return "success";
    }

    @RequestMapping("/test3")
    @ResponseBody
    public Object test23(@Validated @RequestBody ListValidate ve, BindingResult br) {
        if (br.hasErrors()) {
            List<ObjectError> errors = br.getAllErrors();
            ObjectError error = errors.get(0);
            return "code:" + error.getCode() + " msg:" + error.getDefaultMessage() + " objectName:" + error.getObjectName() + " arguments:" + error.getArguments();
        }
        for (ValidateEntity v : ve.getVes())
            System.out.println(v + ":------");
        return "success";
    }

}
